define(function(require, exports, module){
    var services = angular.module('ModuleResolver', []);

    // 参考 : http://weblogs.asp.net/dwahlin/archive/2013/05/22/dynamically-loading-controllers-and-views-with-angularjs-and-requirejs.aspx
    services.provider('moduleResolver', function () {

        this.$get = function () {
            return this;
        };

        var resolveDependencies = function ($q, $rootScope, dependencies) {
                var defer = $q.defer();
                //console.log(arguments,require);
                seajs.use(dependencies, function () {
                    defer.resolve();
                    // 跳过scope脏检查
                    safeApply($rootScope, function(){});
                    //$rootScope.$$phase || $rootScope.$apply();
                });

                return defer.promise;
            },
            safeApply = function (scope, fn) {
                (scope.$$phase || scope.$root.$$phase) ? fn() : scope.$apply(fn);
            };

        this.resolve = function (routeDef) {
            //var routeDef = {};
            //routeDef.templateUrl = routeConfig.getViewsDirectory() + baseName + '.html';
            //routeDef.controller = baseName + 'Controller';

            // 是否配置scriptUrl
            if(routeDef["scriptUrl"]){

                // 判断module是否已存在
                // xxx
                //console.log(routeDef["templateUrl"]);
                routeDef.resolve = {
                    load: ['$q', '$rootScope', function ($q, $rootScope) {
                        var dependencies = [routeDef.scriptUrl];
                        return resolveDependencies($q, $rootScope, dependencies);
                    }]
                };
            }

            return routeDef;
        };
    });
    return services;
});